package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.dao.PaasFormExplainDao;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.ProductDTO;
import com.xbongbong.saas.base.EnumBase;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.saas.script.tempenum.TempWarehouseEnum;
import com.xbongbong.saas.service.RepairWarehouseExplainService;
import com.xbongbong.sys.constant.PaasFormTableNameConstant;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.xbongbong.saas.script.help.InitExplainsHelper.commonFiledInit;

/**
 * @author: wujian
 * @create: 2021-01-28 17:21
 * @description:
 **/
@Service("RepairWarehouseExplainService")
public class RepairWarehouseExplainServiceImpl implements RepairWarehouseExplainService {

    private static final Logger LOG = LoggerFactory.getLogger(RepairWarehouseExplainServiceImpl.class);

    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasFormExplainDao paasFormExplainDao;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Override
    public String repairWarehouseExplain(ProductDTO productDTO) throws XbbException {
        LOG.warn("----------------repairWarehouseExplain begin-------------------");
        long start = DateTimeUtil.getInt();

        TempWarehouseEnum senderDatails = TempWarehouseEnum.SENDER_DATAILS;

        WarehouseEnum anEnum = senderDatails.getAnEnum();
        // 包装业务枚举类
        EnumBase<WarehouseEnum> enumBase = new EnumBase<>(anEnum);
        Class<?> clazz = enumBase.t.getClass();
        // 获取业务枚举类中的属性，以集合的形式返回，同一个枚举的属性值只获取一次
        List<String> enumAttrs = InitExplainsHelper.getBusinessEnumAttrs(clazz);

        // 收货信息字段解释
        FieldAttrEntity fieldAttrEntity = InitExplainsHelper.setField(enumBase, enumAttrs);
        if (fieldAttrEntity != null){
            String saasAttr = fieldAttrEntity.getSaasAttr();
            String attr = saasAttr.substring(0, 1).toUpperCase() + saasAttr.substring(1);
            String methodName = "init" + attr;
            try {
                commonFiledInit(fieldAttrEntity);
                Method method = TempWarehouseEnum.class.getMethod(methodName, FieldAttrEntity.class);
                method.invoke(senderDatails, fieldAttrEntity);
            } catch (NoSuchMethodException e) {
                LOG.warn("未找到对应字段的初始化方法");
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
            fieldAttrEntity.setDefaultName(senderDatails.getAnEnum().getAttrName());
        }

        List<String> corpidList = productDTO.getCorpidList();

        // corpid 为0的默认解释 刷入新字段
        PaasFormExplainEntity defaultExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode(), BasicConstant.ZERO_STRING);
        List<FieldAttrEntity> defaultExplainList = JSONArray.parseArray(defaultExplain.getExplains(), FieldAttrEntity.class);
        //判断没有该解释的添加 有的就跳过
        List<String> defaultAttrList = new ArrayList<>();
        for (FieldAttrEntity attrEntity : defaultExplainList) {
            defaultAttrList.add(attrEntity.getAttr());
        }
        if(!defaultAttrList.contains(WarehouseEnum.SENDER_DETAILS.getAttr())){
            defaultExplainList.add(fieldAttrEntity);
            // 更新表单解释
            defaultExplain.setExplains(JSONObject.toJSONString(defaultExplainList));
            try {
                paasFormExplainModel.update(defaultExplain);
            } catch (Exception e) {
                LOG.error("表单解释更新失败", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
        }

        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("共需更新公司" + corpidList.size() + "家");
        int count = 0;
        int notRepaire = 0;
        for (String corpid : corpidList) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainDao.getByBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode(), corpid, PaasFormTableNameConstant.TB_PAAS_FORM_EXPLAIN);
            // 解释为空的走默认解释
            if (Objects.isNull(paasFormExplainEntity) || Objects.equals("[]", paasFormExplainEntity.getExplains())){
                ++ notRepaire;
                LOG.warn("corpid: " + corpid + "走默认解释无需更新!");
                LOG.warn("当前已更新" + count + "家公司，当总前进度" + count+notRepaire + "/" + + corpidList.size());
                continue;
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            if (Objects.nonNull(explainList)){
                List<String> attrList = new ArrayList<>();
                for (FieldAttrEntity attrEntity : explainList) {
                    attrList.add(attrEntity.getAttr());
                }
                if (!attrList.contains(WarehouseEnum.SENDER_DETAILS.getAttr())){
                    explainList.add(fieldAttrEntity);
                    // 更新表单解释
                    paasFormExplainEntity.setExplains(JSONObject.toJSONString(explainList));
                    try {
                        paasFormExplainModel.update(paasFormExplainEntity);
                        ++ count;
                        LOG.warn("corpid: " + corpid + "已更新完毕！");
                        LOG.warn("当前已更新" + count + "家公司，当总前进度" + count+notRepaire + "/" + + corpidList.size());
                    } catch (Exception e) {
                        LOG.error("表单解释更新失败", e);
                        LOG.warn(corpid + "更新失败，已更新进度" + count + "/" + corpidList.size());
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                }else {
                    LOG.warn(corpid + "该公司已经存在" + fieldAttrEntity.getAttr() + "字段");
                }
            }

        }
        JSONObject object = new JSONObject();
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功,本次共更新" + corpidList.size() + "家公司，其中:" + count + " 家已更新，" + "走默认解释公司共：" + notRepaire + "家");
        object.put("success", "成功");
        return object.toJSONString();
    }
}
